package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.RedisConstant;
import com.itheima.dao.SetMealDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Order;
import com.itheima.pojo.Setmeal;
import com.itheima.service.SetMealService;
import freemarker.template.Configuration;
import freemarker.template.Template;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;
import redis.clients.jedis.JedisPool;

import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service(interfaceClass = SetMealService.class)
@Transactional
public class SetMealServiceImpl implements SetMealService {
    @Autowired
    private JedisPool jedisPool;
    @Autowired
    private SetMealDao setMealDao;
    @Autowired
    private FreeMarkerConfigurer freeMarkerConfigurer;

    @Value("${out_put_path}")
    private String outPutPath;//从属性文件中读取要生成的html对应的目录



    @Override
    public List<Map<String, Object>> findSetmealNameAndCount() {

        return setMealDao.findSetmealNameAndCount();
    }

    @Override
    public void add(int[] ids, Setmeal setmeal) {
        setMealDao.add(setmeal);
        Integer setmealId = setmeal.getId();
        if(ids!=null && ids.length>0){
            for (int checkgroupId : ids) {
                setMealDao.setSetmealAndCheckgroup(setmealId,checkgroupId);

            }
        }
        jedisPool.getResource().sadd(RedisConstant.SETMEAL_PIC_DB_RESOURCES,setmeal.getImg());
        //当添加套餐后需要重新生成静态页面（套餐列表页面、套餐详情页面）
        generateMobileStaticHtml();
    }
    //生成当前方法所需的静态页面
    public void generateMobileStaticHtml(){
        //在生成静态页面之前需要查询数据
        List<Setmeal> list = setMealDao.findAll();
        System.out.println(list);

        //需要生成套餐列表静态页面
        generateMobileSetmealListHtml(list);

        //需要生成套餐详情静态页面
        generateMobileSetmealDetailHtml(list);
    }

    //生成套餐列表静态页面
    public void generateMobileSetmealListHtml(List<Setmeal> list){
        Map map = new HashMap();
        //为模板提供数据，用于生成静态页面
        map.put("setmealList",list);
        generteHtml("mobile_setmeal.ftl","m_setmeal.html",map);
    }

    //生成套餐详情静态页面（可能有多个）
    public void generateMobileSetmealDetailHtml(List<Setmeal> list){
        for (Setmeal setmeal : list) {
            Map map = new HashMap();
            map.put("setmeal",setMealDao.findById(setmeal.getId()));
            generteHtml("mobile_setmeal_detail.ftl","setmeal_detail_" + setmeal.getId() + ".html",map);
        }
    }

    //通用的方法，用于生成静态页面
    public void generteHtml(String templateName,String htmlPageName,Map map){
        Configuration configuration = freeMarkerConfigurer.getConfiguration();//获得配置对象
        Writer out = null;
        try {
            Template template = configuration.getTemplate(templateName);
            //构造输出流
            out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(outPutPath + "/" + htmlPageName)),"UTF-8"));
//            out = new FileWriter(new File(outPutPath + "/" + htmlPageName));
            //输出文件
            template.process(map,out);
            out.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
//        获取三个参数
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        String queryString = queryPageBean.getQueryString();
        //开启分页
        PageHelper.startPage(currentPage,pageSize);
        //查询并赋值给Page托管类
        Page<Setmeal> page=setMealDao.findPage(queryString);
        long total = page.getTotal();
        List<Setmeal> result = page.getResult();
        return new PageResult(total,result);

    }


//    预约管理代码
    @Override
    public void edit(Integer[] ids, Setmeal setmeal) {
        //        修改检查组基本信息,操作t_checkgroup表
        setMealDao.edit(setmeal);
//        清理当前检查组关联检查项,操作中间表t_setmeal_checkgroup
        setMealDao.deleteAssociation(setmeal.getId());
//        重新建立当前检查组和检查项的关联
        Integer setmealId = setmeal.getId();
        if (ids != null && ids.length > 0) {
            for (Integer checkGroupId : ids) {
//                Map<String, Integer> map = new HashMap<>();
                setMealDao.setSetmealAndCheckgroup(setmealId,checkGroupId);
            }
        }
    }

    @Override
    public boolean deleteById(int id) {
//        这里先查询一下是否有人预约该套餐,否则不能删除
        List<Order> list = setMealDao.findIsOrderedBySetmealId(id);
        if(list!=null&&list.size()>0){

//        先删除关联项
            setMealDao.deleteAssociation(id);
            setMealDao.deleteById(id);
            return true;
        }
        return false;
    }

    @Override
    public List<Integer> findGroupById(int id) {
       return setMealDao.findGroupById(id);
    }

    @Override
    public List<Setmeal> findAll() {

        return setMealDao.findAll();
    }

    @Override
    public Setmeal findOnlySetmealById(int id) {
        return setMealDao.findOnlySetmealById(id);
    }


}
